package org.lewis.demo.util;

import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class ParamUtil {

    /**
     * 按key的字典序排序，用拼接符拼接value
     *
     * @param delimiter 拼接符
     * @param param     接口参数
     * @return
     */
    public String values(CharSequence delimiter, Map<String, Object> param) {
        if (ObjectUtils.isEmpty(param)) {
            return null;
        }

        List<String> list = param.entrySet().stream()
                .filter(e -> !e.getKey().equals("sign")).filter(e -> StringUtils.hasText(e.getValue().toString()))
                .sorted(Map.Entry.comparingByKey())
                .map(e -> e.getValue().toString()).collect(Collectors.toList());

        return String.join(delimiter, list);
    }

    /**
     * 按key的字典序排序，去除value为空的参数，以key=value形式，用拼接符拼接
     *
     * @param delimiter 拼接符
     * @param param     接口参数
     * @return
     */
    public String keyValues(CharSequence delimiter, Map<String, Object> param) {
        if (ObjectUtils.isEmpty(param)) {
            return null;
        }

        List<String> list = param.entrySet().stream()
                .filter(e -> !e.getKey().equals("sign")).filter(e -> StringUtils.hasText(e.getValue().toString()))
                .sorted(Map.Entry.comparingByKey())
                .map(e -> String.join("=", e.getKey(), e.getValue().toString())).collect(Collectors.toList());

        return String.join(delimiter, list);
    }

}
